package com.patui.Logic;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import com.patui.DataCache.AccoutConfigure;
import com.patui.DataStructure.MsgInfo;
import com.patui.Utils.PLog;
import com.patui.Weibo.RequestToken;
import com.patui.Weibo.Weibo;
import com.patui.Weibo.WeiboException;
public class FrameSevice extends Service implements Runnable{
	public final static String TAG="FrameSevice";
	public final static String SPLITTER="___";
	public static List<Activity> allActivity = new ArrayList<Activity>();
	public static List<MyTask> allTask = new ArrayList<MyTask>();
	public boolean isRun = true;
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		isRun=true;
		Thread mThread=new Thread(this);
		mThread.start();
	}

	public static void addNewTask(MyTask newTask)
	{
		allTask.add(newTask);
	}
	
	public static void saveUserInfo(String userName,String passWord,String userId)
	{
		AccoutConfigure.setSinaToken(userName);
		AccoutConfigure.setSinaTokenSecret(passWord);
		AccoutConfigure.setSinaUserId(userId);
		AccoutConfigure.saveLoginInfo();
	}
	public static void addLoginTask(int curWeibo)
	{
		 Map<String,Object> map=new HashMap<String, Object>();
		 map.put("curWeibo", curWeibo);
		 MyTask loginTask=new MyTask(MyTask.TASK_LOGIN,map);
		 addNewTask(loginTask);
	}
	
	public static void addStartActivityTask(MsgInfo msgObject)
	{
		 Map<String,Object> map=new HashMap<String, Object>();
		 map.put("msginfo", msgObject);
		 MyTask activiytTask=new MyTask(MyTask.START_ACTIVITY,map);
		 addNewTask(activiytTask);
	}
	
	
	public void startActivity(MsgInfo msg)
	{
		Intent intent = new Intent();  
		intent.setClassName(getApplicationContext(), msg.activityName);
		Bundle bundle=new Bundle();
		bundle.putString("url", msg.url);
		intent.putExtras(bundle);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		this.startActivity(intent);
	}
	public void loginWeibo(int curWeibo) {
			// TODO Auto-generated method stub
		Weibo mWeibo=Weibo.getInstance();
	    String url=null;
	    try {
			RequestToken requestToken = mWeibo.getRequestToken(this, Weibo.APP_KEY, 
					Weibo.APP_SECRET, Weibo.callBackUrl);
			mWeibo.setRequestToken(requestToken);
			String oauth_token=requestToken.getToken();
			oauth_token = "oauth_token="+oauth_token;
			url=Weibo.URL_AUTHORIZE+"?"+oauth_token;
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			PLog.e(TAG,"Exception:"+e.toString());
			url=null;
			e.printStackTrace();
		}
		if(url!=null)
		{
			Intent intent = new Intent(); 
			intent.putExtra("loadUrl", url);
			intent.setClassName(getApplicationContext(), AlllActivityName.LoginWebViewActivity);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			this.startActivity(intent);
		}
		
	}
	
	public void doTask(MyTask doTask)
	{
		Message msg=mHandler.obtainMessage();
		msg.what=doTask.getTaskId();
		try {
			switch (doTask.getTaskId()) {
			case MyTask.TASK_LOGIN:
				Map<String, Object> loginMap = doTask.getMapParams();
				Object curWeibo=loginMap.get("curWeibo");
				msg.arg1=(Integer)curWeibo;
				break;
				
			case MyTask.START_ACTIVITY:
				Map<String, Object> startActMap = doTask.getMapParams();
				Object curActivity=startActMap.get("msginfo");
				msg.obj=curActivity;
				break;
			default:
				break;
			}
			
		} catch (Exception e) {
			PLog.e(TAG,"Exception:"+e.toString());
			msg.what=-1;
			// TODO: handle exception
		}finally{
			
		}
		mHandler.sendMessage(msg);
		allTask.remove(doTask);
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(isRun)
		{
			MyTask theTask=null;
			synchronized (allTask) 
			{
				if(allTask.size()>0)
				{
					theTask=allTask.get(0);
					doTask(theTask);
				}
			}
			try {
				Thread.sleep(500);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		
	}
	
	private MainHandler mHandler=new MainHandler();
	
	//
	class MainHandler extends Handler
	{

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case MyTask.TASK_LOGIN:
				int curWeibo=msg.arg1;
				loginWeibo(curWeibo);
				break;
			case MyTask.START_ACTIVITY:
				MsgInfo actMsg=(MsgInfo)msg.obj;
				startActivity(actMsg);
				break;
			default:
				break;
			}
		}
		
	}
	public static void addActivity(Activity nameOfActivity)
	{
		if(!allActivity.contains(nameOfActivity))
		{
			allActivity.add(nameOfActivity);
		}
	}
	
	public static Activity getActivityByName(String serchActName)
	{
		for(Activity mActivity:allActivity)
		{
			if(mActivity.getClass().getName().indexOf(serchActName)>=0)
			{
				return mActivity;
			}
		}
		return null;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		isRun=false;
		System.exit(0);
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	public static void exitApp(Context ctx)
	{
		for(Activity mActivity:allActivity)
		{
			mActivity.finish();
		}
		Intent intent=new Intent("com.patui.Logic.FrameService");
		ctx.stopService(intent);
	}

}
